/** 
 * @file Accelerometer.c
 * 
 * @detail Description : 
 * Accelerometer function calls 
 * 
 * @author E. Macias / D. Torres / S. Ravindran
 * @author Texas Instruments, Inc
 * @date December, 2011
 * @version 1.0 - Initial version
 * @note Built with IAR Embedded Workbench: 5.20.1 and CCS Version 5.1.0.09000
 **/

/* ************************* ADXL345 Accelerometer *************************** */

#include "Accelerometer.h"

/**
* @brief <b>Function Name</b>:     : Init_Accelerometer                                               
* @brief  <b>Description</b>: This function initializes the accelerometer, by 
* enabling the measurement mode and the full resolution mode.
* @param Input Parameters: None
* @return Return Values: None
**/ 
void Init_Accelerometer(void)
{

  // Accelerometer
  I2C_Set_Slave_Address(ADXL345_ADDR);
	
  global_tx_buffer[0] = 0x2D;	// Power Register
  global_tx_buffer[1] = 0x08; 	// Measurement Mode
  
  I2C_Write_Packet_To_Sensor(&global_tx_buffer[0],2);
  Sleep(20);
  
  global_tx_buffer[0] = 0x31;	// Data Format Register
  global_tx_buffer[1] = 0x08; 	// Full Resolution
  I2C_Write_Packet_To_Sensor(&global_tx_buffer[0],2);
  Sleep(20);

}

/**
* @brief <b>Function Name</b>:     : Read_Accelerometer                                               
* @brief  <b>Description</b>: This function reads the accelerometer's x, y, and 
* z value, stores it in the sen_data structure. Afterwards it subtracts the 
* offset from the raw values, and changes the sign for the necessary axes.
* @param Input Parameters: None
* @return Return Values: None
**/ 
void Read_Accelerometer(void)
{
  uint8_t rx_temp_buffer[6];
  
  // Accelerometer
  I2C_Set_Slave_Address(ADXL345_ADDR);
  
  rx_temp_buffer[0] = 0x32;		// Starting Address (X-Axis[0]) 
  I2C_Read_Packet_From_Sensor(&rx_temp_buffer[0],6);
  
  /******************************** Read raw data *****************************/

  // X axis
  sen_data.accel_x_raw = ( ((int16_t)rx_temp_buffer[1]) << 8) | rx_temp_buffer[0];
  // Y axis 
  sen_data.accel_y_raw = ( ((int16_t)rx_temp_buffer[3]) << 8) | rx_temp_buffer[2];  
  // Z axis 
  sen_data.accel_z_raw = ( ((int16_t)rx_temp_buffer[5]) << 8) | rx_temp_buffer[4];
      
  /***************************** Subtract the offset **************************/
  sen_data.accel_x = sen_data.accel_x_raw - sen_offset.accel_offset[0];
  sen_data.accel_y = sen_data.accel_y_raw - sen_offset.accel_offset[1];
  sen_data.accel_z = sen_data.accel_z_raw - sen_offset.accel_offset[2];
      
  /************************** Change the sign if needed ***********************/
  sen_data.accel_x *= -1* SENSOR_SIGN[3];
  sen_data.accel_y *= -1* SENSOR_SIGN[4];
  sen_data.accel_z *= -1* SENSOR_SIGN[5];   

}
